<template>
  <div class="contioner" v-loading="pageData.loadingUp">
    <a-tabs :lazy-load="true" justify @change="tabChange" :default-active-key="pageData.active">
      <a-tab-pane key="1" title="借用单">
        <pageTabelLayout>
          <template #pageHeader>
            <div class="my-tool-bar" style="margin-bottom: 5px">
              <a-space>
                <el-button type="primary" :icon="Search" @click="getList">查询</el-button>
                <el-button type="success" :icon="CirclePlus" @click="newData('新增')"
                  >新增</el-button
                >
                <el-button :icon="EditPen" @click="audit">审核</el-button>
                <el-button plain @click="TurnDown">驳回</el-button>
                <el-button plain :icon="Delete" @click="deleteData">删除</el-button>
              </a-space>
            </div>
          </template>
          <!-- <div style="background-color: #f0f2f5; height: 10px"></div> -->
          <template #pageTabel>
            <encapsulation-agrid
              ref="refgridOption"
              :configaggrid="configaggrid"
            ></encapsulation-agrid>
          </template>
        </pageTabelLayout>
      </a-tab-pane>
      <a-tab-pane key="2" title="借用单已审核">
        <pageTabelLayout>
          <template #pageHeader>
            <div class="search-form isheader" v-show="pageData.headerShow">
              <a-form size="small" :model="query" layout="inline">
                <CorporateSectorCascader
                  :style="{ width: '200px' }"
                  :configCascader="configCascader"
                  @changeCascader="changeCascader"
                />
                <a-form-item label="借出单号">
                  <a-input
                    allow-clear
                    :style="{ width: '180px' }"
                    class="bacClass"
                    v-model="pageData.needCode"
                  />
                </a-form-item>
                <a-form-item label="借出人">
                  <a-input
                    allow-clear
                    :style="{ width: '180px' }"
                    class="bacClass"
                    v-model="pageData.needPerson"
                  />
                </a-form-item>
                <a-form-item label="审核状态">
                  <a-select
                    allow-clear
                    :style="{ width: '180px' }"
                    class="bacClass"
                    v-model="pageData.auditState"
                  >
                    <a-option value="1">审核通过</a-option>
                    <a-option value="2">驳回</a-option>
                  </a-select>
                </a-form-item>
              </a-form>
            </div>
            <div class="my-divisders">
              <a-divider orientation="center">
                <icon-double-up
                  v-if="pageData.headerShow"
                  @click="pageData.headerShow = false"
                  :strokeWidth="2"
                  :size="18"
                />
                <icon-double-down
                  v-else
                  @click="pageData.headerShow = true"
                  :strokeWidth="2"
                  :size="18"
                />
              </a-divider>
            </div>
            <div class="my-tool-bar">
              <a-space>
                <el-button type="primary" :icon="Search" @click="getList">查询</el-button>
              </a-space>
            </div>
          </template>
          <!-- <div style="background-color: #f0f2f5; height: 10px"></div> -->
          <template #pageTabel>
            <encapsulation-agrid
              ref="refgridOption1"
              :configaggrid="configaggrid1"
            ></encapsulation-agrid>
          </template>
        </pageTabelLayout>
      </a-tab-pane>
    </a-tabs>

    <a-drawer
      cancel-text="关闭"
      ok-text="保存"
      popup-container=".arco-tabs-content"
      height="91vh"
      placement="bottom"
      :visible="pageData.showAdd"
      unmountOnClose
      @cancel="pageData.showAdd = false"
      @ok="save"
      :mask-closable="false"
    >
      <template #title> {{ pageData.type }}</template>
      <el-form ref="ruleFormRef" :model="query" label-width="88px" class="demo-query" status-icon>
        <el-row :gutter="24">
          <!-- <CorporateSectorCascader
              ref="cascaderRef1"
              :configCascader="configCascader1"
              @changeCascader="changeCascader1"
            /> -->
          <el-col :span="12" style="display: flex">
            <!-- <el-form-item label="公司" prop="companyName">
              <el-input v-model="query.companyName" style="width: 200px" disabled />
            </el-form-item> -->
            <CorporateSectorCascader
              ref="cascaderRef3"
              :configCascader="configCascader3"
              @changeCascader="changeCascader3"
            />
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="公司部门" prop="departmentName">
              <el-input v-model="query.departmentName" style="width: 200px" disabled />
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12"  style="display:flex;">
            <CorporateSectorCascader
              ref="cascaderRef1"
              :configCascader="configCascader1"
              @changeCascader="changeCascader1"
            />
          </el-col> -->
          <el-col :span="6" style="display: flex">
            <CorporateSectorCascader
              ref="cascaderRef2"
              :configCascader="configCascader2"
              @changeCascader="changeCascader2"
            />
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="借出时间"
              prop="needTime"
              :rules="[{ required: true, message: '借出时间必选' }]"
            >
              <el-date-picker
                type="date"
                placeholder="选择借出时间"
                v-model="query.needTime"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 200px"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="借出单号"
              prop="needCode"
              :rules="[{ required: true, message: '借出单号必选' }]"
            >
              <el-input v-model="query.needCode" style="width: 200px" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="借出人" prop="needPerson">
              <el-input v-model="query.needPerson" style="width: 200px" disabled />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="6">
            <el-form-item label="借用仓库" prop="warehouseId">
              <el-select  v-model="query.warehouseId"  style="width: 200px" :disabled="( query.borrowCompanyID == query.companyID) || !query.borrowCompanyID" >
                <el-option v-for="item in warehouseNameList" :key="item.id" :label="item.warehouseName" :value="item.id"  />
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>

        <el-row :gutter="24">
          <!-- <el-col :span="6">
            <el-form-item
              label="借用机台"
              prop="mechanicalCode"
              :rules="[{ required: true, message: '借用机台必选' }]"
            >
              <el-select-v2
                v-model="query.mechanicalCode"
                :options="repairmanList"
                placeholder="选择借用机台"
                filterable
                :loading="pageData.loadingUp"
                clearable
                @change="selectV2"
                size="default"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="机台类别"
              prop="mechanicalType"
              :rules="[{ required: true, message: '机台类别必选' }]"
            >
              <el-input v-model="query.mechanicalType" style="width: 200px" disabled />
            </el-form-item>
          </el-col> -->
        </el-row>
        <!-- <el-row :gutter="24">
          <el-col :span="6">
            <el-form-item
              label="何时归还"
              prop="returnsTime"
              :rules="[{ required: true, message: '何时归还必选' }]"
            >
              <el-input v-model="query.returnsTime" style="width: 200px" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="借用期"
              prop="borrowNumer"
              :rules="[{ required: true, message: '借用期必选' }]"
            >
              <el-input v-model="query.borrowNumer" style="width: 200px" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="借用期时间"
              prop="borrowTime"
              :rules="[{ required: true, message: '借用期时间必选' }]"
              label-width="100px"
            >
              <el-input v-model="query.borrowTime" style="width: 200px" disabled />
            </el-form-item>
          </el-col>
        </el-row> -->
      </el-form>
      <div class="hengxian"></div>
      <el-button style="margin-left: 15px" :icon="CirclePlus" @click="addWorkbench" type="success"
        >固定资产编号</el-button
      >
      <el-button style="margin-left: 30px" :icon="Delete" @click="deleteWorkbench" type="warning"
        >删除</el-button
      >
      <div :style="{ height: '78%', padding: '10px' }" style="background: #fff">
        <encapsulation-agrid
          ref="refgridOption2"
          :configaggrid="configaggrid2"
        ></encapsulation-agrid>
      </div>
    </a-drawer>
    <a-drawer
      cancel-text="关闭"
      ok-text="保存"
      popup-container=".arco-tabs-content"
      height="91vh"
      placement="bottom"
      :visible="pageData.workbenchShowAdd"
      unmountOnClose
      @cancel="pageData.workbenchShowAdd = false"
      @ok="stockKeeping"
      :mask-closable="false"
      style="z-index: 999"
    >
      <template #title> 选取固定资产 </template>
      <div style="width: 100%; height: 90%">
        <el-form :model="query" label-width="100px" class="demo-query" status-icon size="default">
          <el-row :gutter="24">
            <el-col :span="4">
              <el-form-item label="物料名称" prop="materialName">
                <!-- <el-select-v2 v-model="query1.mechanicalName" :options="MaterialNameList" placeholder="选择物料名称" filterable
                  :loading="pageData.loadingUp" clearable size="default" /> -->
                <el-input v-model="query1.materialName" placeholder="输入物料名称" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="物料编号" prop="materialCode">
                <!-- <el-select-v2 v-model="query1.materialCode" :options="MaterialNumberList" placeholder="选择物料编号" filterable
                  :loading="pageData.loadingUp" clearable size="default" /> -->
                <el-input v-model="query1.materialCode" placeholder="输入物料编号" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="固定资产编号">
                <el-input v-model="query1.numberId" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="所属区域" prop="district">
                <!-- <el-select-v2 v-model="TheyAreFixedAssets.district" :options="seclectList.districtList"
                  placeholder="选择所属区域" filterable :loading="pageData.loadingUp" clearable size="default" /> -->
                <el-input v-model="query1.district" placeholder="输入所属区域" />
              </el-form-item>
            </el-col>
            <el-col :span="4" style="display: flex; justify-content: flex-end; align-items: center">
              <el-button type="primary" :icon="Search" @click="workbenchGetList">查询</el-button>
            </el-col>
          </el-row>
        </el-form>
        <encapsulation-agrid
          ref="refgridOption3"
          :configaggrid="configaggrid3"
        ></encapsulation-agrid>
      </div>
    </a-drawer>
    <el-dialog
      align-center
      style="width: 1200px; height: 450px"
      v-model="pageData.dialogFormVules"
      v-loading="loadingElplus"
    >
      <!-- <div style="width: 100%; height: 450px"> -->
      <AgGridVuesCopys
        :rowHeight="33"
        :headerHeight="33"
        :suppressCopyRowsToClipboard="true"
        rowSelection="multiple"
        @grid-ready="gridReady"
        style="height: 37vh"
        :defaultColDef="defaultColDef"
        class="ag-theme-alpine"
        :rowData="pageData.dataListOP"
        :columnDefs="tableColumns4"
        :localeText="localeText1"
      >
      </AgGridVuesCopys>
      <!-- </div> -->
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
  // 引入element提示
  import { ElMessage, ElMessageBox } from 'element-plus'
  //引入封装post
  import { post } from '@/api/http'
  
  import { localeText } from '@/api/aggridZw'
  import {
    tableColumns,
    tableColumns1,
    tableColumns2,
    tableColumns4,
  } from './BorrowingOfFixedAssets'
  import buttionRender from '@/components/aggridCellRenDerer/buttionRender.vue'
  import { Search, Delete, CirclePlus, EditPen } from '@element-plus/icons-vue'
  import CorporateSectorCascader from '@/components/corporateSectorCascader1/index.vue'
  import { ref, watch } from 'vue'
  import { DateFilterModelFormatter } from 'ag-grid-community/dist/lib/filter/provided/date/dateFilter'
  import dayjs from 'dayjs'
  import { slicing } from '@/utils/caseFrimAndSecRig'
  import emitter from '@/hooks/useEventBus'
  const loadingElplus = ref(false)
  const gridOption = ref()
  const gridReady = (params: any) => {
    gridOption.value = params.api
  }
  const defaultColDef = {
    sortable: true,
    resizable: true,
    filter: true,
  }
  const localeText1: any = ref(localeText)
  let pageData = reactive<any>({
    showAdd: false,
    workbenchShowAdd: false,
    type: '',
    loadingUp: false,
    active: '1',
    headerShow: true,
    id: '',
    companyID: '',
    companyName: '',
    mechanicalCode: '',
    needCode: '',
    needPerson: '',
    departmentName: '',
    departmentID: '',
    id1: '',
    dataListOP: [],
    auditState: '',
  })
  let query = reactive<any>({
    mechanicalName: '',
    mechanicalType: '',
    needTime: '',
    returnsTime: '',
    borrowNumer: '',
    borrowTime: '',
    companyName: '',
    companyID: '',
    departmentName: '',
    departmentID: '',
    needCode: '',
    needPerson: '',
    needDepartmentName: '',
    needDepartmentID: '',
    borrowCompanyName: '',
    borrowCompanyID: '',
    warehouseName: '', //仓库名称
    warehouseId: '', //仓库id
    warehouseTypeName: '',
  })

  let query1 = reactive<any>({
    materialCode: '',
    mechanicalName: '',
    companyId: query.companyID,
    outDepartmentId: query.departmentID,
    numberId: '',
  })
  tableColumns.push({
    headerName: '操作',
    field: 'ouihadpc',
    resizable: 'false',
    filter: false,
    sortable: 'false',
    width: 185,
    // lockPosition: 'right',
    pinned: 'right',
    cellRenderer: buttionRender,
    cellRendererParams: {
      buttonList: [
        {
          type: 'success',
          text: '修改',
          typeName: 'el-button',
          Callback: (data: any) => {
            for (let key in data) {
              query[key] = data[key]
            }
            newData('修改', data)
          },
        },
        {
          type: 'success',
          text: '详情',
          typeName: 'el-button',
          Callback: (data: any) => {
            for (let key in data) {
              query[key] = data[key]
            }
            newData('详情', data)
          },
        },
      ],
      eltagSize: 0,
    },
  })
  tableColumns1.push({
    headerName: '操作',
    field: 'ouihadpc',
    resizable: 'false',
    filter: false,
    sortable: 'false',
    width: 185,
    // lockPosition: 'right',
    pinned: 'right',
    cellRenderer: buttionRender,
    cellRendererParams: {
      buttonList: [
        {
          type: 'success',
          text: '详情',
          typeName: 'el-button',
          Callback: (data: any) => {
            for (let key in data) {
              query[key] = data[key]
            }
            newData('详情', data)
          },
        },
      ],
      eltagSize: 0,
    },
  })
  let form = reactive<any>({
    deleteState: 0,
  })
  let cascaderRef = ref('')
  let configCascader = ref<{}>({
    corporateWidth: '180px', //公司宽度
    sectorWidth: '180px', //部门宽度
    corporateRquired: false, //公司是否必填
    sectorRquired: false, //部门是否必填
    size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '借入公司', //公司label
    sectorName: '借入部门', //部门label
    cascaderShow: '', //配置部门不显示
  })
  const changeCascader = (data: any) => {
    const { corporateId, corporateLabel, sectorLabel, sectorId } = data
    // console.log('data',data)

    pageData.companyName = corporateLabel
    pageData.companyID = corporateId
    pageData.departmentName = sectorLabel
    pageData.departmentID = sectorId
  }
  let cascaderRef1 = ref()
  // let configCascader1 = ref<{}>({
  //   corporateWidth: '65%', //公司宽度
  //   sectorWidth: '65%', //部门宽度
  //   corporateRquired: true, //公司是否必填
  //   sectorRquired: true, //部门是否必填
  //   size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
  //   corporateName: '借入公司', //公司label
  //   sectorName: '借入部门', //部门label
  //   cascaderShow: '', //配置部门不显示
  //   sectorNameLabelWidth: '78px',
  //   corporateNameLabelWidth: '78px',
  // })
  const configCascader1 = ref<{}>({
    corporateWidth: '65%', //公司宽度
    size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '公司', //公司label
    cascaderShow: 'sector', //配置部门不显示
    corporateRquired: true,
    corporateNameLabelWidth: '78px',
  })
  const changeCascader1 = (data: any) => {
    const { corporateId, corporateLabel, sectorLabel, sectorId } = data
    console.log(data)
    query.companyName = corporateLabel
    query.companyID = corporateId
    // query.needDepartmentName = sectorLabel
    // query.needDepartmentID = sectorId
  }
  let cascaderRef2 = ref()
  let configCascader2 = ref<{}>({
    corporateWidth: '65%', //公司宽度
    sectorWidth: '65%', //部门宽度
    corporateRquired: true, //公司是否必填
    sectorRquired: false, //部门是否必填
    size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '借入公司', //公司label
    sectorName: '借入部门', //部门label
    cascaderShow: 'sector', //配置部门不显示
    sectorNameLabelWidth: '78px',
    corporateNameLabelWidth: '78px',
  })
  const warehouseNameList: any = ref([])
  const changeCascader2 = async (data: any) => {
    const { corporateId, corporateLabel, sectorLabel, sectorId } = data
    // console.log(data)
    query.borrowCompanyName = corporateLabel
    query.borrowCompanyID = corporateId

    if (!query.borrowCompanyName) {
      setTimeout(() => {
        refgridOption2.value.setdataListIterface(
          refgridOption2.value.getListData().map((res: any) => {
            res.usePerson = null
            res.borrowDepartmentID = null
            res.borrowDepartmentName = null
            return res
          })
        )
      }, 0)
    }
    if (query.borrowCompanyID == query.companyID || !query.borrowCompanyID) {
      //先重置借用仓库的值
      query.warehouseName = ''
      return
    }
    const res = await post({
      url: 'wms/warehouse/getFieldValue2',
      data: {
        firmId: query.borrowCompanyID,
        warehouseName: '',
        warehouseTypeName: '五金仓',
      },
    })
    warehouseNameList.value = res.data
    query.warehouseName = warehouseNameList.value[0].warehouseName
    query.warehouseTypeName = warehouseNameList.value[0].warehouseTypeName
    query.warehouseId = warehouseNameList.value[0].id
    console.log(warehouseNameList.value)
  }
  // watch(() => query.warehouseId, (val) => {
  //   const a = warehouseNameList.value.find((item: any) => item.id == val)
  //   query.warehouseName = a.warehouseName
  //   query.warehouseTypeName = a.warehouseTypeName
  // })
  let refgridOption = ref<any>()
  let refgridOption1 = ref<any>()
  let refgridOption2 = ref<any>()
  let refgridOption3 = ref<any>()
  let configaggrid = ref({
    url: 'purchase/FixedAssetsBorrow/getPage', //接口路径
    queryData: {
      deleteState: 0,
      auditState: 0,
    },
    paginationShow: true, //分页是否显示
    invokeiIterface: true, //是否调用接口
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns,
    fileName: 'BorrowingOfFixedAssets-1',
  })
  let configaggrid1 = ref({
    url: 'purchase/FixedAssetsBorrow/getPage', //接口路径
    queryData: {
      deleteState: 0,
      auditState: pageData.auditState,
    },
    paginationShow: true, //分页是否显示
    invokeiIterface: true, //是否调用接口
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns1,
    fileName: 'BorrowingOfFixedAssets-2',
  })

  let tableColumns3: any = [
    {
      headerCheckboxSelection: true,
      checkboxSelection: true,
      width: 60,
      showDisabledCheckboxes: false,
      pinned: 'left',
    },
    {
      headerName: '公司',
      field: 'companyName',
      width: 230,
    },
    {
      headerName: '物料编号',
      field: 'materialCode',
      width: 230,
    },
    {
      headerName: '物料名称',
      field: 'materialName',
      width: 230,
    },
    {
      headerName: '固定资产编号',
      field: 'numberId',
      width: 230,
    },
    {
      headerName: '物料小类',
      field: 'majorCategory',
      width: 230,
    },
    {
      headerName: '借入部门',
      field: 'borrowDepartmentID',
      width: 220,
      cellRenderer: {
        template: `
               <div>
               <a-cascader v-model="res.borrowDepartmentID" :options="dataList" allow-clear ref="casOb1"
                  style="width: 180px;"  class="bacClass" @click="b" popup-container="html"
                  @change="a"  :title="res.title1"/>
               </div>
                  `,
        setup(props: any) {
          const res = ref(props.params.data)
          const dataList: any = ref()
          const casOb1: any = ref()
          onMounted(() => {
            post({
              url: `org/baCompany/getDepartmentTree?companyId=${query.borrowCompanyID} `,
            }).then(({ data }) => {
              dataList.value = data
            })
          })
          const a = (val: any) => {
            res.value.usePerson = ''
            if (casOb1.value?.selectViewValue.length != 0) {
              res.value.title1 = slicing(casOb1.value?.selectViewValue[0]['label'])
              res.value.borrowDepartmentName = slicing(casOb1.value?.selectViewValue[0]['label'])
            }
          }
          const b = async () => {
            if (query.borrowCompanyID) {
              const { code, data } = await post({
                url: `org/baCompany/getDepartmentTree?companyId=${query.borrowCompanyID} `,
              })
              if (code == 200) {
                dataList.value = data
              }
            }
          }
          return {
            res,
            a,
            dataList,
            b,
            casOb1,
          }
        },
      },
    },
    {
      headerName: '使用人',
      field: 'usePerson',
      width: 220,
      cellRenderer: {
        template: `
      <div @click="viewModal" ><a-input  v-model="res.usePerson" class="bacClass" /></div>
           
           <a-modal v-model:visible="visible" :on-before-ok
           ="handleOk" @cancel="handleCancel" width="800px">
           <template #title>使用人</template>
           <a-spin dot :loading="loading" class="w-full h-full">
               <div class="flex justify-between	">
               <el-form @submit.native.prevent>
               <el-form-item label="员工名称" prop="queryName">
                       <el-input v-model="queryName" style="width: 200px" />
               </el-form-item>
               </el-form>
               <el-button type="primary" :icon="Search" @click="getUsers1">查询</el-button>
               </div>
               <div > <AgGridVuesCopys
                   :rowHeight="33"
                   :headerHeight="33"
                   :suppressCopyRowsToClipboard="true"
                   rowSelection="single"
                   @grid-ready="gridReady"
                   style="height: 37vh"
                   :defaultColDef="defaultColDef"
                   class="ag-theme-alpine"
                   :rowData="dataListOP"
                   :columnDefs="formColumns"
                   :localeText="localeText"
               >
               </AgGridVuesCopys>
               
               </div>
               <div class="flex justify-center	"><el-pagination
               small
               background
               layout="prev, pager, next"
               :total="pagination.total"
               v-model:current-page="pagination.page"
               class="mt-4"
               @current-change ="getUsers1"/>
               </div>
           </a-spin>
           </a-modal>
                 `,
        setup(props: any) {
          const dataListOp: any = ref()
          const loading = ref(false)
          const visible = ref(false)
          const res = ref(props.params.data)
          const queryName = ref('')
          const gridOption = ref()
          const pagination = ref({
            page: 1,
            size: 10,
            total: 0,
          })
          const gridReady = (params: any) => {
            gridOption.value = params.api
          }
          const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
          }
          const formData = ref([])
          const formColumns = [
            {
              headerCheckboxSelection: false,
              checkboxSelection: true,
              width: 60,
              filter: false,
              sortable: false,
              resizable: false,
              showDisabledCheckboxes: false,
              pinned: 'left',
            },
            {
              headerName: '员工名称',
              field: 'name',
              width: 150,
            },
            {
              headerName: '员工工号',
              field: 'code',
              width: 150,
            },
            {
              headerName: '岗位名称',
              field: 'postName',
              width: 200,
            },
          ]
          const getUsers1 = () => {
            loading.value = true
            console.log(res, 'res')

            post({
              url: 'org/hrEmployee/getPage',
              data: {
                deleteState: 0,
                obsoleteState: 0,
                company_id: query.borrowCompanyID,
                ygText: queryName.value,
                page: pagination.value.page,
                size: pagination.value.size,
                department_id: res.value.borrowDepartmentID,
              },
            }).then(({ data, code }: any) => {
              if (code === 200) {
                dataListOp.value = data.list
                console.log(dataListOp.value)
                pagination.value.total = data.total
                loading.value = false
                gridOption.value.setRowData(data.list)
              } else {
                Message.error({
                  content: '该部门无员工信息！',
                  duration: 5000,
                })
                loading.value = false
              }
            })
          }
          const handleOk = () => {
            console.log(res)
            if (gridOption.value.getSelectedRows().length === 0) {
              ElMessage.warning('请勾选您要填入的员工！')
              return false
            } else {
              res.value.usePerson = gridOption.value.getSelectedRows()[0].name
              return true
            }
            visible.value = false
          }
          const handleCancel = () => {
            visible.value = false
          }
          const viewModal = () => {
            if (!res.value.borrowDepartmentID) {
              ElMessage.warning('请先选择借入部门！')
              return
            }
            queryName.value = ''
            pagination.total = 0
            pagination.value.page = 1
            loading.value = false
            if (res.value.usePerson) queryName.value = res.value.usePerson

            getUsers1()
            visible.value = true
          }
          return {
            res,
            getUsers1,
            visible,
            dataListOp,
            loading,
            handleOk,
            viewModal,
            queryName,
            gridOption,
            gridReady,
            formColumns,
            formData,
            localeText,
            defaultColDef,
            Search,
            pagination,
            ElMessage,
          }
        },
      },
    },
    {
      headerName: '何时归还',
      field: 'scrapTime',
      width: 230,
      cellRenderer: {
        template: `
                <a-date-picker  popup-container="html"  v-model="res.scrapTime" @change='a'>
                </a-date-picker>
            `,
        setup(props: any) {
          const res = ref(props.params.data)
          res.value.deprecitionTime = dayjs(res.value.scrapTime).diff(dayjs(query.needTime), 'day')
          const a = () => {
            res.value.deprecitionTime = dayjs(res.value.scrapTime).diff(
              dayjs(query.needTime),
              'day'
            )
            const listData = JSON.parse(JSON.stringify(refgridOption2.value.getListData()))
            nextTick(() => {
              refgridOption2.value.setdataListIterface(listData)
            })
          }
          return {
            res,
            a,
          }
        },
      },
    },
    {
      headerName: '借用期(天)',
      field: 'deprecitionTime',
      width: 230,
    },
    {
      headerName: '分摊类型',
      field: 'shareType',
      width: 230,
    },
  ]
  const isRowSelectable = (rowNode: any) => {
    console.log(rowNode.data.machineState, rowNode.data.subCategory)

    // if (
    //   rowNode.data.machineState != 0 &&
    //   (rowNode.data.subCategory === '单面机' ||
    //     rowNode.data.subCategory === '双面机' ||
    //     rowNode.data.subCategory === '罗纹机')
    // ) {
    //   return false
    // }
    if (rowNode.data.type == '设备' || rowNode.data.type == '针筒') {
      return false
    }
    return true
  }
  let configaggrid2 = ref({
    url: '', //接口路径
    queryData: {
      deleteState: 0,
      auditState: 1,
    },
    paginationShow: false, //分页是否显示
    invokeiIterface: false, //是否调用接口
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns3,
  })
  let configaggrid3 = ref({
    url: 'wms/ironwareStockInfo/getList', //接口路径
    queryData: {
      mechanicalName: '',
      mechanicalCode: '',
      companyId: query.companyID,
      outDepartmentId: query.departmentID,
    },
    paginationShow: true, //分页是否显示
    invokeiIterface: false, //是否调用接口
    rowMultiSelectWithClick: true, //点击行是否多选
    column: tableColumns2,
    selectable: isRowSelectable,
    rowStyle: (rowNode: any) => {
      //   if(rowNode.data.machineState!=0&&(rowNode.data.subCategory==='单面机'||rowNode.data.subCategory==='双面机'||rowNode.data.subCategory==='罗纹机')){
      //   return { background: 'lightgrey' };
      // }
      if (rowNode.data.type == '设备' || rowNode.data.type == '针筒') {
        return { background: 'lightgrey' }
      }
      return null
    },
  })
  const newData = async (type: string, data?: any) => {
    pageData.type = type
    repairmanFocus()
    if (type == '新增') {
      for (let key in query) {
        query[key] = ''
      }
      pageData.id = ''
      try {
        pageData.loadingUp = true
        let { code, message, data } = await post({
          url: 'purchase/FixedAssetsBorrow/getNeedCode',
        })
        if (code == 200) {
          pageData.loadingUp = false
          acquisitionCompany()
          query.needCode = data
          return
        }
        ElMessage.error(message)
      } finally {
        pageData.loadingUp = false
      }
    }
    if (type == '修改') {
      pageData.showAdd = true
      nextTick(() => {
        const {
          companyID,
          companyName,
          departmentID,
          departmentName,
          id,
          borrowCompanyName,
          borrowCompanyID,
          needDepartmentName,
          needDepartmentID,
          list,
        } = data
        let pam = {
          sectorId: departmentID,
          sectorLabel: departmentName,
          corporateId: companyID,
          corporateLabel: companyName,
        }
        let pam1 = {
          sectorId: needDepartmentID,
          sectorLabel: needDepartmentName,
          corporateId: borrowCompanyID,
          corporateLabel: borrowCompanyName,
        }
        cascaderRef3.value?.parentComponent(pam)
        cascaderRef2.value?.parentComponent(pam1)
        post({
          url: '/purchase/FixedAssetsBorrowDetail/getList',
          data: {
            fixedAssetsBorrowID: id,
          },
        }).then(({ code, data }) => {
          if (code == 200) {
            // refgridTheyAreFixedAssetsAggrid.value.setdataListIterface([...data])
            refgridOption2.value.setdataListIterface([...data])
          }
        })
        pageData.id = id
      })
    }
    if (type == '详情') {
      post({
        url: '/purchase/FixedAssetsBorrowDetail/getList',
        data: {
          fixedAssetsBorrowID: data.id,
        },
      }).then(({ code, data }) => {
        if (code == 200) {
          // refgridTheyAreFixedAssetsAggrid.value.setdataListIterface([...data])
          // refgridOption2.value.setdataListIterface([...data])
          pageData.dataListOP = data
        }
      })
      pageData.dialogFormVules = true
    }
  }
  const workbenchGetList = () => {
    query1.companyId = query.companyID
    query1.outDepartmentId = query.departmentID
    refgridOption3.value.setQuery({ stockState: 1, ...query1 })
  }
  // //物料名称
  let MaterialNameList = ref<any>([])
  // //物料编号
  let MaterialNumberList = ref<any>([])
  //查询物料名称接口
  const MaterialNameFocus = async () => {
    try {
      pageData.loadingUp2 = true
      let res: any = await post({
        url: 'wms/ironwareStockInfo/getFieldValueTwo',
        data: {
          materialCode: '',
          filterMap: {
            outFirmId: query.companyID,
            outDepartmentId: query.departmentID,
            stockState: 1,
          },
        },
      })
      if (res.code == 200) {
        MaterialNumberList.value = res.data.map((item: any) => {
          return {
            value: item.materialCode,
            label: item.materialCode,
          }
        })
        pageData.loadingUp2 = false
        return
      }
      ElMessage.error(res.message)
    } finally {
      pageData.loadingUp2 = false
    }
  }
  //查询物料名称接口
  const MaterialNameFocus1 = async () => {
    try {
      pageData.loadingUp2 = true
      let res: any = await post({
        url: 'wms/ironwareStockInfo/getFieldValueTwo',
        data: {
          materialName: '',
          filterMap: {
            outFirmId: query.companyID,
            outDepartmentId: query.departmentID,
            stockState: 1,
          },
        },
      })
      if (res.code == 200) {
        MaterialNameList.value = res.data.map((item: any) => {
          return {
            value: item.materialName,
            label: item.materialName,
          }
        })
        pageData.loadingUp2 = false
        return
      }
      ElMessage.error(res.message)
    } finally {
      pageData.loadingUp2 = false
    }
  }
  //删除机台
  const deleteWorkbench = () => {
    const selectedData = refgridOption2.value.getSelectedRows()
    if (selectedData.length == 0) {
      ElMessage.warning('请勾选您要删除的单据')
      return
    }
    ElMessageBox.confirm('确认删除选中单据?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(() => {
        refgridOption2.value.applyTransaction({ remove: selectedData })
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      })
      .catch(() => {})
  }
  const addWorkbench = () => {
    if (!query.needTime) {
      ElMessage({
        type: 'error',
        message: '请选择借出时间',
      })
      return
    }
    pageData.workbenchShowAdd = true
    nextTick(() => {
      workbenchGetList()
      MaterialNameFocus()
      MaterialNameFocus1()
    })
  }
  //机台保存
  const stockKeeping = () => {
    let arr3 = refgridOption3.value.getSelectedRows()
    if (arr3.length == 0) {
      ElMessage.warning('请勾选您要选择的机台')
      return
    }
    let arr = refgridOption2.value.getListData()
    for (const item of arr) {
      const found = arr3.find((elem: any) => elem.numberId === item.numberId)
      if (!found) {
        arr3.push(item)
      }
    }
    const newArr = arr3.map((item: any) => {
      if (item.hasOwnProperty('fixedAssetsBorrowState')) {
        return {
          ...item,
          fixedAssetsBorrowState: 1,
        }
      }
      return item
    })
    refgridOption2.value.setdataListIterface([...newArr])
    pageData.workbenchShowAdd = false
  }
  let cascaderRef3: any = ref()
  let configCascader3 = ref<{}>({
    corporateWidth: '190px', //公司宽度
    sectorWidth: '190px', //部门宽度
    corporateRquired: true, //公司是否必填
    sectorRquired: true, //部门是否必填
    size: 'small', //选择框大小'mini' | 'small' | 'medium' | 'large'
    corporateName: '公司', //公司label
    sectorName: '部门名称', //部门label
    cascaderShow: '', //配置部门不显示
    sectorNameLabelWidth: '78px',
    corporateNameLabelWidth: '78px',
  })
  const changeCascader3 = async (data: any) => {
    console.log(data)
    const { corporateId, corporateLabel, sectorLabel, sectorId } = data
    query.companyName = corporateLabel
    query.companyID = corporateId
    query.departmentName = sectorLabel
    query.departmentID = sectorId
  }
  const acquisitionCompany = async () => {
    try {
      pageData.loadingUp = true
      let { code, message, data } = await post({
        url: 'admin/acl/user/findUserToken',
      })
      if (code == 200) {
        const { firmId, firmName, userName, department, departmentId } = data.data
        query.companyID = firmId
        query.companyName = firmName
        query.needPerson = userName
        query.departmentID = departmentId
        query.departmentName = department
        pageData.showAdd = true
        nextTick(() => {
          cascaderRef3.value?.parentComponent({
            sectorId: departmentId,
            corporateId: firmId,
            corporateLabel: firmName,
            sectorLabel: department,
          })
        })
        pageData.loadingUp = false
        return
      }
      ElMessage.error(message)
    } finally {
      pageData.loadingUp = false
    }
  }
  const deleteData = () => {
    const selectedData = refgridOption.value.getSelectedRows()
    if (selectedData.length == 0) {
      ElMessage.warning('请勾选您要删除的单据')
      return
    }
    let condition = selectedData.every((item: any) => item.auditState == 1)
    if (condition) {
      ElMessage.warning('状态为审核通过不可删除!')
      return
    }
    ElMessageBox.confirm('确认删除选中单据?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          pageData.loadingUp = true
          let arr: any
          arr = []
          selectedData.map((item: any) => {
            arr.push(item.id)
          })
          let { code, message } = await post({
            url: 'purchase/FixedAssetsBorrow/delete',
            data: arr,
          })
          if (code == 200) {
            ElMessage.success('删除成功')
            pageData.loadingUp = false
            getList()
            return
          }
          ElMessage.error(message)
        } finally {
          pageData.loadingUp = false
        }
      })
      .catch(() => {})
  }
  const ruleFormRef = ref<any>()
  let stadey: boolean = true
  const save = async () => {
    console.log(refgridOption2.value.getListData())
    if (!query.borrowCompanyName) {
      ElMessage.warning('请选择借入公司')
      return
    }

    const selectedData = refgridOption2.value.getListData()
    if (selectedData.length == 0) {
      ElMessage.warning(`请勾选您的单据`)
      return
    }
    query.list = selectedData
    try {
      await ruleFormRef.value.validate()
      stadey = refgridOption2.value.getListData().every((item: any) => {
        return new Date(item.scrapTime) > new Date(query.needTime)
      })
      if (stadey) {
        if (pageData.type == '新增') {
          try {
            pageData.loadingUp = true
            let { code, message } = await post({
              url: 'purchase/FixedAssetsBorrow/insert',
              data: query,
            })
            if (code == 200) {
              ElMessage.success('新增成功')
              pageData.loadingUp = false
              getList()
              pageData.showAdd = false
              return
            }
            ElMessage.error(message)
          } finally {
            pageData.loadingUp = false
          }
        }
        if (pageData.type == '修改') {
          let pam = query
          pam.id = pageData.id
          try {
            pageData.loadingUp = true
            let { code, message } = await post({
              url: 'purchase/FixedAssetsBorrow/update',
              data: pam,
            })
            if (code == 200) {
              ElMessage.success('修改成功')
              pageData.loadingUp = false
              getList()
              pageData.showAdd = false
              return
            }
            ElMessage.error(message)
          } finally {
            pageData.loadingUp = false
          }
        }
      } else {
        ElMessage.error('归还时间不能超过借出时间！')
      }
    } catch (error) {
      // 表单验证失败，可以执行相应的错误处理逻辑
    }
  }
  const TurnDown = () => {
    const selectedData = refgridOption.value.getSelectedRows()
    if (selectedData.length == 0) {
      ElMessage.warning('请勾选您要驳回的单据')
      return
    }
    if (selectedData.every((item: any) => item.auditState == 1)) {
      ElMessage.warning('状态为审核通过不可驳回!')
      return
    }
    ElMessageBox.confirm('确认驳回选中单据?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          pageData.loadingUp = true
          let arr: any
          arr = []
          selectedData.map((item: any) => {
            arr.push({
              id: item.id,
              auditState: '2',
            })
          })
          let { code, message } = await post({
            url: 'purchase/FixedAssetsBorrow/setAudit',
            data: arr,
          })
          if (code == 200) {
            ElMessage.success('驳回成功')
            pageData.loadingUp = false
            getList()
            return
          }
          ElMessage.error(message)
        } finally {
          pageData.loadingUp = false
        }
      })
      .catch(() => {})
  }
  const audit = () => {
    const selectedData = refgridOption.value.getSelectedRows()
    if (selectedData.length == 0) {
      ElMessage.warning('请勾选您要审核的单据')
      return
    }
    let condition = selectedData.every((item: any) => item.auditState == 1)
    if (condition) {
      ElMessage.warning('状态为审核通过不可审核!')
      return
    }
    ElMessageBox.confirm('确认审核选中单据?', '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        try {
          pageData.loadingUp = true
          let arr: any
          arr = []
          selectedData.map((item: any) => {
            arr.push({
              id: item.id,
              auditState: '1',
            })
          })
          let { code, message } = await post({
            url: 'purchase/FixedAssetsBorrow/setAudit',
            data: arr,
          })
          if (code == 200) {
            ElMessage.success('审核成功')
            pageData.loadingUp = false
            getList()
            // refgridOption.value.setQuery(query)
            return
          }
          ElMessage.error(message)
        } finally {
          pageData.loadingUp = false
        }
      })
      .catch(() => {})
  }
  onMounted(() => {
    getList()
    repairmanFocus()
  })
  const getList = () => {
    if (pageData.active == '1') {
      form.auditState = 0
      nextTick(() => {
        refgridOption.value.setQuery(form)
      })
    }
    if (pageData.active == '2') {
      form.auditState = 1
      let pam = { ...form }
      pam.needCode = pageData.needCode
      // pam.borrowCompanyName = pageData.companyName
      pam.companyID = pageData.companyID
      pam.needPerson = pageData.needPerson
      // pam.needDepartmentName = pageData.departmentName
      pam.needDepartmentID = pageData.departmentID
      pam.auditState = pageData.auditState
      nextTick(() => {
        refgridOption1.value.setQuery(pam)
      })
    }
  }
  const tabChange = (tab: any) => {
    emitter.emit('window-change')
    pageData.active = tab
    getList()
  }
  //机台
  let repairmanList = ref<any>([])
  //查询机台接口
  const repairmanFocus = async () => {
    try {
      pageData.loadingUp = true
      let res: any = await post({
        url: 'purchase/FixedInitialize/getFieldValue',
        data: {
          mechanicalCode: '',
        },
      })
      if (res.code == 200) {
        res.data.map((item: any) => {
          item.value = item.mechanicalCode
          item.label = item.mechanicalName + '-' + item.mechanicalCode
        })
        repairmanList.value = res.data
        pageData.loadingUp = false
        return
      }
      ElMessage.error(res.message)
    } finally {
      pageData.loadingUp = false
    }
  }
  const selectV2 = async (data: any) => {
    console.log(data)
    if (!data) {
      query.mechanicalType = ''
      query.returnsTime = ''
      query.borrowNumer = ''
      query.borrowTime = ''
      query.mechanicalName = ''
      return
    }
    let pam = {
      mechanicalCode: '',
      mechanicalName: '',
    }
    repairmanList.value.map((item: any) => {
      if (item.mechanicalCode == data) {
        pam = {
          mechanicalCode: item.mechanicalCode,
          mechanicalName: item.mechanicalName,
        }
      }
    })
    // query.mechanicalCode = pam.mechanicalCode
    try {
      pageData.loadingUp = true
      let { code, message, data } = await post({
        url: 'purchase/FixedInitialize/getList',
        data: pam,
      })
      if (code == 200) {
        const { scrapTime, deprecitionTime, shareType, mechanicalType, mechanicalName } = data
        query.mechanicalType = mechanicalType
        query.returnsTime = scrapTime
        query.borrowNumer = deprecitionTime
        query.borrowTime = shareType
        query.mechanicalName = mechanicalName

        pageData.loadingUp = false
        return
      }
      ElMessage.error(message)
    } finally {
      pageData.loadingUp = false
    }
    console.log(pam)
  }
</script>
<script lang="ts">
  export default defineComponent({
    name: 'BorrowingOfFixedAssets',
  })
</script>
<style scoped>
  .contioner {
    height: 100%;
    background-color: #fff;
  }

  .contentPrint {
    width: 100%;
    display: flex;
    justify-content: space-between;

    color: #000 !important;
  }

  .printLeft {
    width: 56%;
  }

  .printTitle {
    font-size: 22px;
    font-weight: 700;
    margin-top: 20px;
  }

  .printRight {
    width: 43%;
    display: flex;
    justify-content: space-between;
    flex-flow: row wrap;
  }

  .ermPrint {
    display: flex;
    justify-content: center;
    /* flex-flow: column wrap; */
    align-items: center;
  }

  .erm {
    width: 160px;
    height: 50px;
    background: #999;
  }

  .formPrint {
    display: flex;
    justify-content: space-between;
    flex-flow: row wrap;
  }

  .ban {
    width: 50%;
    margin-bottom: 5px;
  }

  .quan {
    width: 100%;
    margin-bottom: 5px;
  }

  table {
    text-align: center;
    color: #000;
  }

  td {
    color: #000;
  }

  th {
    color: #000;
  }

  .tablePrint {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
    flex-flow: row wrap;
  }

  .footerPrint {
    display: flex;
    justify-content: space-around;
    margin-top: 8px;
    color: #000;
  }

  .createTime {
    width: 100px;
  }

  .printw {
    width: 30%;
    margin-bottom: 5px;
  }

  :deep(.el-dialog__body) {
    color: #000;
  }

  .my-tool-bar {
    background: #fff;
    padding: 18px;
  }

  .c-header {
    background: #fff;
    padding: 15px 0 10px 0;
  }

  :deep(.el-input__inner) {
    color: #3b3a3a;
  }

  :deep(.el-input__wrapper) {
    box-shadow: 0 0 0 1px #474849 inset;
  }

  :deep(.el-form-item__label) {
    color: #202021;
  }

  :deep(.arco-drawer-container) {
    z-index: 1000 !important;
  }

  .hengxian {
    height: 5px;
    border-bottom: 1px solid #cecece;
    margin-bottom: 22px;
  }

  :deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
  }

  :deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
  }

  :deep(.ag-header-group-text) {
    text-align: center;
  }

  :deep(.ag-header-group-cell-label, .ag-header-cell-label) {
    justify-content: center !important;
  }
</style>
